import { useVModel } from '../../../utils/hooks'
import { defineComponent, nextTick, PropType } from 'vue'
import { UploadFile } from '../types'
import { Upload } from 'ant-design-vue'

export default defineComponent({
  name: 'SpsFormUpload',
  props: {
    id: {
      type: String
    },
    value: {
      type: Array as PropType<UploadFile[]>,
      default: () => []
    }
  },
  emits: ['update:value', 'blur', 'change'],
  setup(props, { attrs, slots, emit }) {
    const fileListRef = useVModel(props, 'value', emit)
    const request = (file: any) => {
      const { uid, name } = file.file
      fileListRef.value.push({
        uid,
        name,
        status: 'uploading'
      })
      setTimeout(() => {
        const currentFile = fileListRef.value.find((item) => item.uid === uid)
        if (!currentFile) return
        currentFile.uid = `sps-file-${uid}`
        currentFile.status = 'done'
        currentFile.url = 'http://www.baidu.com'
      }, 1500)
    }
    const { onChange, ...otherAttrs } = attrs as any
    const handleChange = ({
      file,
      fileList
    }: {
      file: UploadFile
      fileList: UploadFile[]
    }) => {
      if (file.status === 'removed') {
        fileListRef.value = fileList
      }
      // 待fileList更新后再emit change时间
      nextTick(() => {
        emit('change')
      })
    }
    /* render 函数 */
    return () => {
      return (
        <>
          <Upload
            fileList={fileListRef.value}
            {...otherAttrs}
            customRequest={request}
            onChange={handleChange}>
            {slots.default ? slots.default() : <a-button>上传</a-button>}
          </Upload>
        </>
      )
    }
  }
})
